﻿// ***********************************************************************
// Assembly         : DonNicky.Common
// Author           : donnicky
// Created          : 11-26-2012
//
// Last Modified By : donnicky
// Last Modified On : 11-26-2012
// ***********************************************************************
using System.ComponentModel.DataAnnotations;
using System.IO;

namespace DonNicky.Common.Validation
{
    /// <summary>
    /// Checks if the file has a definite extension
    /// </summary>
    public class FileWithExtensionAttribute : ValidationAttribute
    {
        /// <summary>
        /// Gets or sets the extension.
        /// </summary>
        /// <value>The extension that file must have to be validated. Must be given with preceding dot symbol.</value>
        /// <example><code>Extension = ".txt"</code></example>
        public string Extension { get; set; }

        /// <summary>
        /// Determines whether the specified value of the object is valid.
        /// </summary>
        /// <param name="value">The value of the object to validate.</param>
        /// <returns>true if the specified value is valid; otherwise, false.</returns>
        public override bool IsValid(object value)
        {
            return value == null || string.IsNullOrEmpty(value.ToString()) || !File.Exists(value.ToString()) ||
                   new FileInfo(value.ToString()).Extension.ToLower() == Extension.ToLower();
        }
    }
}
